package cn.zaichi.edu.excelcommon.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;

import cn.zaichi.edu.excelcommon.entity.BaseImportParam;
import cn.zaichi.edu.excelcommon.handler.BaseExcelHandler;
import cn.zaichi.edu.excelcommon.handler.ImportExcelHandler;
import cn.zaichi.edu.excelcommon.process.ExcelImportDataInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * 表头处理工具类
 */
public class ImportWorkbookUtil {
    /**
     * 获取工作表格
     *
     * @param filePath 文件地址，文件密码
     */
    public static Workbook onStart(String filePath,String filePass) throws IOException, GeneralSecurityException {
        InputStream is = new FileInputStream(new File(filePath));
        Workbook hssfWorkbook = null;
       /* if(filePass!=null){

            if (filePath.endsWith("xlsx")) {
                POIFSFileSystem pfs = new POIFSFileSystem(is);
                is.close();
                EncryptionInfo encInfo = new EncryptionInfo(pfs);
                Decryptor decryptor = Decryptor.getInstance(encInfo);
                decryptor.verifyPassword(filePath);
                hssfWorkbook = new XSSFWorkbook(decryptor.getDataStream(pfs));//Excel 2007
            } else if (filePath.endsWith("xls")) {

                //Excel 2003
                org.apache.poi.hssf.record.crypto.Biff8EncryptionKey
                        .setCurrentUserPassword(filePass);
                hssfWorkbook = WorkbookFactory.create(is);
                is.close();

            }
            return hssfWorkbook;
        }*/
        if (filePath.endsWith("xlsx")) {
            hssfWorkbook = new XSSFWorkbook(is);//Excel 2007
        } else if (filePath.endsWith("xls")) {
            hssfWorkbook = new HSSFWorkbook(is);//Excel 2003
        }
        is.close();
        return hssfWorkbook;
    }

    /**
     * 设置Handler
     * @param importDataInfo
     * @param sheet
     */
    public static BaseExcelHandler getExcelHandler(BaseExcelHandler excelHandler, ExcelImportDataInfo importDataInfo, Sheet sheet, BaseImportParam param){
        //数据行数
        importDataInfo.setRowCount(sheet.getLastRowNum()-param.getStartRow()+1);
        Row row = sheet.getRow(param.getStartRow());
        if(row==null){
            return new ImportExcelHandler(importDataInfo);
        }
        //列数
        int cellCount = row.getLastCellNum() - param.getStartColumn()+1;
        importDataInfo.setColumentCount(cellCount);

        return new ImportExcelHandler(importDataInfo);
    }
}
